from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from models import StockOut, Product, Inventory, db
from utils import error, success
from datetime import datetime, timedelta

stock_out_api = Blueprint('stock_out_api', __name__, url_prefix='/api/stock-out')

@stock_out_api.route('/', methods=['GET'])
@jwt_required()
def get_stock_out_records():
    """获取出库记录列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('page_size', 10, type=int)
        search = request.args.get('search', '')
        product_id = request.args.get('product_id', type=int)
        status = request.args.get('status', '')
        start_date = request.args.get('start_date', '')
        end_date = request.args.get('end_date', '')
        
        query = db.session.query(StockOut, Product).join(Product)
        
        # 搜索过滤
        if search:
            query = query.filter(
                Product.name.contains(search) 
            )
        
        # 商品过滤
        if product_id:
            query = query.filter(StockOut.product_id == product_id)
        
        # 状态过滤
        if status:
            query = query.filter(StockOut.status == status)
        
        # 日期过滤
        if start_date:
            query = query.filter(StockOut.created_at >= datetime.strptime(start_date, '%Y-%m-%d'))
        if end_date:
            query = query.filter(StockOut.created_at <= datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1))
        
        # 按创建时间倒序排列
        query = query.order_by(StockOut.created_at.desc())
        
        # 分页
        pagination = query.paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        records = []
        for stock_out, product in pagination.items:
            records.append({
                'id': stock_out.id,
                'product_id': product.id,
                'product_name': product.name,
                'product_sku': product.sku,
                'quantity': stock_out.quantity,
                'unit_price': stock_out.unit_price,
                'total_amount': stock_out.total_amount,
                'operator_id': stock_out.operator_id,
                'operator_name': stock_out.operator.name if stock_out.operator else None,
                'notes': stock_out.notes,
                'status': stock_out.status,
                'created_at': stock_out.created_at.isoformat(),
                'updated_at': stock_out.updated_at.isoformat()
            })
        
        return success(data={
            'records': records,
            'total': pagination.total,
            'pagination': {
                'page': pagination.page,
                'page_size': pagination.per_page,
                'total': pagination.total
            }
        }).to_response()
        
    except Exception as e:
        return error(500, f'Failed to get stock out records: {str(e)}').to_response()


@stock_out_api.route('/', methods=['POST'])
@jwt_required()
def create_stock_out_record():
    """创建出库记录"""
    try:
        data = request.get_json()
        user_id = get_jwt_identity()
        
        # 验证必填字段 - 简化后只需要商品ID和数量
        if not data.get('product_id'):
            return error(code=400, msg='商品ID不能为空').to_response()
        if not data.get('quantity'):
            return error(code=400, msg='出库数量不能为空').to_response()
        
        product_id = data['product_id']
        quantity = int(data['quantity'])
        
        if quantity <= 0:
            return error(code=400, msg='出库数量必须大于0').to_response()
        
        # 检查商品是否存在
        product = Product.query.get_or_404(product_id)
        
        # 检查库存是否充足
        inventory = Inventory.query.filter_by(product_id=product_id).first()
        if not inventory:
            # 如果库存记录不存在，创建一个
            inventory = Inventory(
                product_id=product_id,
                current_stock=0,
                reserved_stock=0,
                available_stock=0
            )
            db.session.add(inventory)
        
        if inventory.available_stock < quantity:
            return error(code=400, msg='库存不足').to_response()
        
        # 使用商品的销售价作为单价
        unit_price = product.unit_price
        total_amount = quantity * unit_price
        
        # 创建出库记录
        stock_out = StockOut(
            product_id=product_id,
            quantity=quantity,
            unit_price=unit_price,
            total_amount=total_amount,
            operator_id=user_id,
            notes=data.get('notes', ''),  # 支持备注
            status='completed'
        )
        
        db.session.add(stock_out)
        
        # 更新库存
        inventory.current_stock -= quantity
        inventory.available_stock = inventory.current_stock - inventory.reserved_stock
        inventory.last_updated = datetime.utcnow()
        
        # 更新商品的库存数量字段（如果存在）
        if hasattr(product, 'stock_quantity'):
            product.stock_quantity = inventory.current_stock
            product.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '出库记录创建成功',
            'data': {
                'id': stock_out.id,
                'product_name': product.name,
                'quantity': quantity,
                'total_amount': total_amount
            }
        })
        
    except Exception as e:
        db.session.rollback()
        return error(500, f'Failed to create stock out record: {str(e)}').to_response()

